﻿using Jack.RemoteLog;
using JMS;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using Way.Lib;

namespace CheckIn.PlanHost
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

            var builder = new ConfigurationBuilder();
            builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            Global.Configuration = builder.Build();

            var port = Global.Configuration.GetValue<int>("Port"); //提供微服务的端口
            var serviceAddress = Global.Configuration.GetValue<string>("ServiceAddress");

            //网关地址
            Global.GatewayAddresses = Global.Configuration.GetSection("Gateways").Get<NetAddress[]>();

            ServiceCollection services = InitServices();

            var msp = new MicroServiceHost(services);
            if (string.IsNullOrEmpty(serviceAddress) == false)
            {
                //自定义微服务地址
                msp.ServiceAddress = new NetAddress(serviceAddress, port);
            }
            msp.Register<Controllers.CheckInController>("CheckInService", "打卡服务", true);
            msp.ServiceProviderBuilded += Msp_ServiceProviderBuilded;
            msp.Build(port, Global.GatewayAddresses, true)
                .Run();
        }

        public static ServiceCollection InitServices()
        {
            ServiceCollection services = new ServiceCollection();
            services.AddSingleton<IConfiguration>(Global.Configuration);
            services.AddScoped<PlanDBContext>();

            services.RegisterService();

            //身份验证
            services.AddJwtTokenAuthentication(Global.Configuration["JwtSecret"], new string[] { "Authorization" });

            return services;
        }
        private static void Msp_ServiceProviderBuilded(object sender, IServiceProvider e)
        {
            Global.ServiceProvider = e;
            var logger = e.GetService<ILogger<Program>>();

            using ( var db = new PlanDBContext())
            {
                //db.Database.ExecSqlString("update checkinhistory set openuserids=null where jsonb_array_length(openuserids)=0");
            }

                logger.LogInformation("启动完毕");
        }
    }
}
